package com.project.bookstore.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.bookstore.common.CommonResult;
import com.project.bookstore.exception.ServiceInternalException;
import com.project.bookstore.user.domain.Address;
import com.project.bookstore.user.pojo.AddressCreateVO;
import com.project.bookstore.user.service.AddressService;
import com.project.bookstore.user.mapper.AddressMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author 12603
 * @description 针对表【t_address(收货地址)】的数据库操作Service实现
 * @createDate 2022-05-14 20:12:16
 */
@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public CommonResult addAddress(Long userId, AddressCreateVO addressCreateVO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressCreateVO, address);
        address.setCreated(LocalDateTime.now())
                .setModified(LocalDateTime.now())
                .setProvince(addressCreateVO.getAddress().get(0))
                .setCity(addressCreateVO.getAddress().get(1))
                .setArea(addressCreateVO.getAddress().get(2))
                .setUserId(userId);
        if (addressCreateVO.getIsDefault() == 1) {
            if (addressMapper.updateIsDefault0(userId) != 1)
                log.warn("数据库中用户ID【{}】的默认地址不为一", addressCreateVO.getUserId());
            log.debug("设置之前的默认地址为非默认地址");
        }
        if (addressMapper.insert(address) != 1) {
            log.warn("插入新地址时发生未知错误userId【{}】", userId);
            throw new ServiceInternalException();
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult updateAdd(Long addressId, AddressCreateVO addressCreateVO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressCreateVO, address);
        address.setModified(LocalDateTime.now())
                .setProvince(addressCreateVO.getAddress().get(0))
                .setCity(addressCreateVO.getAddress().get(1))
                .setArea(addressCreateVO.getAddress().get(2));
        if (addressCreateVO.getIsDefault() == 1) {
            if (addressMapper.updateIsDefault0(addressCreateVO.getUserId()) != 1) {
                log.warn("数据库中用户ID【{}】的默认地址不为一", addressCreateVO.getUserId());
            }
            log.debug("设置之前的默认地址为非默认地址");
        }
        if (addressMapper.myUpdateById(addressId, address) != 1) {
            log.warn("修改地址时发生未知错误");
            throw new ServiceInternalException();
        }
        return CommonResult.ok();
    }
}




